package com.bringway.global.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import com.bringway.global.dao.SysLogDao;
import com.bringway.global.domain.SysUserDetails;
import com.bringway.p2p.dao.P2PUserDao;

/*
* @author 作者 xuef
* @version 创建时间：2015年11月30日 上午10:31:57
* 类说明
*/
public class SysUserDetailsService implements UserDetailsService{

	@Autowired
	private SysLogDao sysLogDao;
	
	@Autowired
	private P2PUserDao P2PUserDao;
	
	@SuppressWarnings("unused")
	@Override
	public UserDetails loadUserByUsername(String gyh) throws UsernameNotFoundException {
		UserDetails userDetails = null;
		SysUserDetails sysUserDetails = null;
        try {  
            // 搜索数据库以匹配用户登录名.  
        	sysUserDetails = P2PUserDao.login(gyh);
        	sysLogDao.insertLoginLog(gyh);
        	sysUserDetails.setAuthorities(getAuthorities(0));
        	userDetails = sysUserDetails;
        } catch (Exception e) { 
        	e.printStackTrace();
        	sysLogDao.insertExceptionLog(gyh, "登录失败", e);
            throw new UsernameNotFoundException("Error in retrieving user");  
        } 
        if(null == userDetails){
        	throw new UsernameNotFoundException(gyh);
        }
        return userDetails;  
	}
	/** 
     * 获得访问角色权限 
     *  
     * @param access 
     * @return 
     */  
    @SuppressWarnings("deprecation")
	public Collection<GrantedAuthority> getAuthorities(Integer access) {  
  
        List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(2);  
  
        // 所有的用户默认拥有ROLE_USER权限  
        authList.add(new GrantedAuthorityImpl("ROLE_USER"));  
  
        // 如果参数access为1.则拥有ROLE_ADMIN权限  
        if (access.compareTo(1) == 0) {  
            authList.add(new GrantedAuthorityImpl("ROLE_ADMIN"));  
        }  
        return authList;  
    }
}
